import { useEffect } from 'react'
import useGetUserInfo from "./useGetUserInfo.ts";
import { useLocation,useNavigate } from 'react-router-dom';
const useNavPage = (waitingUserData: boolean) =>{
    const { username } = useGetUserInfo()
    const { pathname } = useLocation()
    const nav = useNavigate()
    // 判断当前路由是不是注册页还是登录页
    const isLoginOrRegister = (pathname: string)=>{
        if(['/login','/register'].includes(pathname)){
            return true
        }else{
            return false
        }
    }
    const isNoNeedUserInfo = (pathname: string)=>{ // 是否需要用户信息
        if(['/','/login','/register'].includes(pathname)){ // 这三个不需要用户信息
            return true
        }else {
            return false
        }
    }

    useEffect(()=>{
        if(waitingUserData) return
        // 已经登录
        if(username){
            if(isLoginOrRegister(pathname)){
                nav('/manage/list')
            }
            return
        }else { // 未登录
            if(isNoNeedUserInfo(pathname)){ // 不需要用户信息
                return 
            }else{
                nav('/login')
            }
        }
    },[waitingUserData,username,pathname,nav])
}

export default useNavPage